using System;
using System.Collections;
using System.Data.Common;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using NHibernate.Cfg;

namespace Sentient.Core
{
    public class NHibernateBuilder
    {
        private readonly string _assembly;
        private readonly DbConnectionStringBuilder _connectionString;
        private Configuration _configuration;

        public NHibernateBuilder(string dataSource, string catalog, string assembly)
        {
            _assembly = assembly;
            _connectionString = new SqlConnectionStringBuilder
            {
                DataSource = dataSource,
                InitialCatalog = catalog,
                IntegratedSecurity = true
            };
        }

        public NHibernateBuilder(string connectionString, string assembly)
        {
            _assembly = assembly;
            _connectionString = new DbConnectionStringBuilder
                                    {
                                       ConnectionString = connectionString
                                    };
        }


        public DbConnectionStringBuilder ConnectionString
        {
            get { return _connectionString; }
        }

        public Configuration Configuration
        {
            get
            {
                if (_configuration == null)
                    _configuration = CreateConfiguration();

                 return _configuration;
            }
        }

        private Configuration CreateConfiguration()
        {
            IDictionary props = new Hashtable();
            props["connection.provider"] = "NHibernate.Connection.DriverConnectionProvider";
            props["dialect"] = "NHibernate.Dialect.MsSql2005Dialect";
            props["connection.driver_class"] = "NHibernate.Driver.SqlClientDriver";
            props["connection.connection_string"] = _connectionString.ToString();
            props["show_sql"] = "false";

            var nhibernateConfig = new Configuration();
            nhibernateConfig.SetProperties(props);

            if (string.IsNullOrEmpty(_assembly))
                return nhibernateConfig;

            if (_assembly.ToLower().Contains(".dll"))
            {
                Console.WriteLine("Loading assembly path " + _assembly);
                nhibernateConfig.AddAssembly(Assembly.LoadFile(_assembly));
            }
            else
            {
                Console.WriteLine("Loading assembly " + _assembly);
                nhibernateConfig.AddAssembly(_assembly);
            }

            return nhibernateConfig;
        }
    }
}